package com.appspot.categoryeditor.utils;

import java.util.List;
import java.util.ListIterator;

import com.appspot.categoryeditor.jsonbean.categorygroup.CategoryBean;
import com.appspot.categoryeditor.jsonbean.categorygroup.FolderBean;
import com.appspot.categoryeditor.model.Category;
import com.appspot.categoryeditor.model.Folder;

public final class ModelUtils {

	public static FolderBean createAndTransfer(Folder folderModel) {

		FolderBean folderBean = new FolderBean();
		folderBean.setId(folderModel.getId().getName());
		folderBean.setOrder(folderModel.getOrder());
		List<Category> categoriesModel = folderModel
				.getCategoriesRefs()
				.getModelList();

		for (Category categoryModel : categoriesModel) {
			folderBean.addCategory(createAndTransfer(categoryModel, false));
		}
		
		return folderBean;
		
	}

	public static CategoryBean createAndTransfer(Category categoryModel) {
		return createAndTransfer(categoryModel, true);
	}
	
	public static CategoryBean createAndTransfer(Category categoryModel,
			boolean includeContent) {

		CategoryBean categoryBean = new CategoryBean();
		categoryBean.setId(String.valueOf(categoryModel.getId().getName()));
		categoryBean.setName(categoryModel.getName());
		
			categoryBean.setContent(
					includeContent ? categoryModel.getContent() : ""
				);

		categoryBean.setOrder(categoryModel.getOrder());
		categoryBean.setAccessible(categoryModel.isAccessible());

		return categoryBean;
	}

	public static List<Folder> filterByAccessible(List<Folder> folderModels) {
		
		for(ListIterator<Folder> itFolder
					= folderModels.listIterator(folderModels.size());
					itFolder.hasPrevious(); ){
			
			Folder f = itFolder.previous();
			
			List<Category> categoryModels = f.getCategoriesRefs().getModelList();
			for (ListIterator<Category> itCategory 
						= categoryModels.listIterator(categoryModels.size());
						itCategory.hasPrevious();) {
				
				Category c = itCategory.previous();
				if(!c.isAccessible()){
					itCategory.remove();
				}
				
			}
			
			if(categoryModels.size() == 0){
				itFolder.remove();
			}
		}
		
		return folderModels;
	}

}
